import { ElMessage } from 'element-plus'
import {defineStore} from 'pinia'
import { computed, ref } from 'vue'

interface Token {
  access_token: string
  token_type: string
  refresh_token: string
  expires_in: number
  user_id: string
}

export const useTokenStore = defineStore('mytoken', ()=>{
  // 相当于state
  const tokenJson = ref("")

  // computed 相当于 getter
  const token = computed<Token>(() => {
    try {
      return JSON.parse(tokenJson.value ||
        window.localStorage.getItem("TokenInfo") || "{}")
    }catch(err) {
      ElMessage.error("json解析失败")
      window.localStorage.setItem("TokenInfo", "")
      throw err
    }
  })

  // function 相当于 actions
  function saveToken(data:string) {
    tokenJson.value = data
    window.localStorage.setItem("TokenInfo", data)
  }

  // 向外暴露
  return {
    token,
    saveToken
  }
})